$().ready(function () {
    var $inputSearch = $("#inputSearch");
    //对搜索输入框的键盘按下后的事件监听
    $inputSearch.on("keyup", function () {
        //获取输入框的值
        var search_text = $inputSearch.val()
        console.log("输入框为" + $inputSearch.val());
        //判断输入框是否为空
        if (search_text == '') {
            console.log("搜索框为空")
        } else {
            //连接数据库进行查询
            $.ajax({
                type: "GET",
                url: "handleSearchServlet",
                data: {"keyword": $inputSearch.val()},
                dataType: "json",
                success: function (data) {
                    console.log(data);
                    //数据库返回的data类型以及有几条数据
                    console.log(typeof (data) + " " + data.length);
                    //返回是json字符串类型时进行转换
                    if (typeof (data) == 'string') {
                        console.log("is string")
                        var stringtoObject = function (data) {
                            return eval("(" + data + ")");
                        }
                        alert(stringtoObject)
                        console.log(stringtoObject);
                    }
                    //创建数组用于存放获取的产品的名字
                    var searchResult = new Array();
                    for (var i = 0; i < data.length; i++) {
                        searchResult[i] = data[i].name;
                        console.log("this is result" + searchResult[i]);
                    }
                    console.log("this is searchResult" + searchResult);
                    $inputSearch.autocomplete({
                        source: searchResult
                    });

                    // var result = [];
                    // var index =0;
                    // $.each(searchResult, function () {
                    //     result.push({'value': data[index].name, 'label': data[index].name, 'image':data[index].description });
                    //     console.log(data[index].name +"+" + data[index].description);
                    //     index++;
                    // });
                    // console.log("this is result" + result[0].value+result[0].label+result[0].image);
                    // console.log("hope"+result);
                    //
                    // $inputSearch.autocomplete({
                    //     'data': result,
                    //
                    //     'itemHeight': 24,
                    //     'width': 280,
                    //     'onerror': function (msg) {
                    //         alert(msg);
                    //     }
                    // });

                }
            })
        }
    });
});
